﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DuplicateContact.aspx.cs" Inherits="CRMWeb.Pages.Contact.DuplicateContact" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Duplicate Client Detection</title>
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/default/easyui.css" />
    <link rel="stylesheet" type="text/css" href="/EasyUI/Themes/icon.css" />
    <link rel="stylesheet" type="text/css" href="/Css/CrmStyle.css" />
    <script type="text/javascript" src="/Scripts/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/EasyUI/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/EasyUI/datagrid-groupview.js"></script>
    <style type="text/css">
        .rowStyle
        {
            display: block;
            border-bottom: 1px solid #AABBCC;
        }

        .CellStyle1
        {
            width: 80px;
            font-weight: bold;
            font-size: 12px;
            height: 20px;
            text-align: left;
        }

        .CellStyle2
        {
            width: 300px;
            font-size: 14px;
            text-align: left;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div style="width: 100%; text-align: center;">
            <div id="pnlDetective" class="easyui-panel" title="Duplicate Client Detect" style="width: auto; height: auto; padding: 5px">
                <div style="vertical-align: middle; padding: 10px; height: auto; width: auto">
                    <label style="width: auto; height: 30px; color: brown; font-weight: bold; font-family: Verdana; text-align: left">Detective Condition : </label>
                    <label style="width: 100px; text-align: right; margin-left: 20px">Multiple :</label>
                    <select id="cmbMultiple" class="easyui-combobox" style="width: 200px">
                        <option value="FullName/DateBirth">Full Name + DOB </option>
                        <option value="FullName/Email">Full Name + Email </option>
                        <option value="FullName/DriverLicense">Full Name + LicenceNO </option>
                        <option value="FullName/app_ipaddress">Full Name + IP </option>
                    </select>
                    <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-search" onclick="detectByMultiple()"></a>
                    <label style="width: 100px; text-align: right; margin-left: 20px">Single :</label>
                    <select id="cmbSingle" class="easyui-combobox" style="width: 200px">
                        <option value="FullName">Full Name </option>
                        <option value="Email">Email </option>
                        <option value="DriverLicense">Licence No</option>
                        <option value="Mobile">Mobile</option>
                        <option value="Address">Address</option>
                    </select>
                    <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-search" onclick="detectBySingle()"></a>
                    <label id="divMsg" style="display: none; width: auto; margin-left: 100px; height: 30px; font-family: Cambria; font-size: medium; color: red; text-align: center">
                        No Duplicate Client matching this condition
                    </label>
                    <input id="hdnDetectiveBy" type="hidden" value="FullName/DateBirth" />
                    <input id="hdnapp_id" type="hidden" />
                    <input id="hdnDetectivBy" type="hidden" />
                    <input id="hdnUserName" type="hidden" runat="server" />
                </div>
                <table style="text-align: left; width: 100%">
                    <tr>
                        <td style="width: 65%">
                            <table id="dgdetectClient"  style="width: auto; height: 550px;" autorowheight="true" pagination="true"
                                data-options="url: '/WebServices/DuplicateContactDetective.ashx?method=GetDuplicateContactAll',
                                pageSize:20, 
                                Collapsible:true,
                                singleSelect:true,
                                rownumbers:true,
                                fitColumns:true,
                                view:groupview,
                                groupField:'FullName',
                                groupFormatter:function(value,rows){
                                return value + ' ' + sptag + '&nbsp&nbsp'+ rows.length + endtag ;
                                }">
                                <thead>
                                    <th field="FullName" hidden="hidden">Full Name</th>
                                    <th field="DetectiveBy" width="40px" align="center" hidden="true">Detective By</th>
                                    <th field="ContactID" width="40px" align="right">Contact ID</th>
                                    <th field="app_id" width="40px" align="center" hidden="true">Form ID</th>
                                    <th field="CreateDate" width="30px" data-options="formatter:formatDate">Create Date</th>
                                    <th field="Profile" width="30px" data-options="formatter:formatCellStyler">Profile Link</th>
                                </thead>
                            </table>
                        </td>
                        <td style="width: 30%; vertical-align: top;">
                            <div id="pnlClientDetail" class="easyui-panel" style="width: 400px; height: 550px; float: left; padding: 5px; display: none">
                                <div class="ftitle">Client Detail Preview</div>
                                <div id="div1" style="text-align: left; width: 350px; height: auto; padding: 10px">
                                    <label id="lbltemp" style="text-decoration: underline; margin-right: 20px; display: none">Client ID : </label>
                                    <label id="lblclientid" style="color: red; font-size: large"></label>
                                    <div id="divpreview" class="fitem" style="height: auto; font-family: Calibri; font-size: medium">
                                    </div>
                                </div>
                                <div id="divappForm" style="height: auto" class="fitem">
                                    <label style="width: 150px; text-align: left">Delete Application(s) :</label>
                                    <select class="easyui-combogrid" id="cmbApplication" style="width: 150px; height: auto;" runat="server" name="cmbapp">
                                    </select>
                                </div>
                                <div style="vertical-align: bottom">
                                    <div class="fitem">
                                        <label style="width: 150px; text-align: left">Duplicate with :</label>
                                        <input id="cmbDuplicateWith" style="width: 150px" class="easyui-combobox" data-options="panelHeight:'100',
                                             onSelect:function(){
                                             ShowClientDetail($('#cmbDuplicateWith').combobox('getValue'));
                                            }" />
                                    </div>
                                    <div class="fitem">
                                        <label style="width: 150px;"></label>
                                        <a id="lnkSave" class="easyui-linkbutton" onclick="SubmitChanges()">Submit</a>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <div id="dlgDeleteConfirm" class="easyui-dialog" title="Confirm" style="width: 300px; height: auto; padding: 10px" closed="true" resizable="false" modal="true">
            <h4 style="text-align: center">Are you sure to delete this application ?</h4>
            <div class="fitem" style="float: left; padding: 10px; margin-top: 10px">
                <a id="lnkDeleteApplication" href="javascript:void(0)" class="easyui-linkbutton" onclick="deleteApplication()" disabled="true">OK</a>
                <a id="lnkCancle" href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#dlgDeleteConfirm').dialog('close')" disabled="true">Cancel</a>
                <span id="spnanimate">
                    <img id="deleteProgress" style="margin-left: 20px" src="../../Media/loading.gif" />
                    <label id="lbltimeOut" style="margin-left: 20px">5</label>
                </span>
            </div>
        </div>
    </form>
</body>
<script type="text/javascript">
    var sptag = '<span style="color:pink;padding-left:10px">';
    var endtag = '</span>';
    var var_deleteApp = '';
    $(document).ready(function () {
        $('#dlgDeleteConfirm').dialog({
            onOpen: function () {
                startCounter(5);
            },
            onClose: function () {
                $('#lnkDeleteApplication').linkbutton('disable');
                $('#lnkCancle').linkbutton('disable');
                $('#spnanimate').show();
                $('#lbltimeOut').html('');
            }
        });
        $('#cmbMultiple').combobox('textbox').bind('click', function () {
            $('#cmbMultiple').combobox('showPanel');
        });
        $('#cmbSingle').combobox('textbox').bind('click', function () {
            $('#cmbSingle').combobox('showPanel');
        });
        $('#cmbApplication').combobox('textbox').bind('click', function () {
            $('#cmbApplication').combobox('showPanel');
        });
        $('#cmbDuplicateWith').combobox('textbox').bind('click', function () {
            $('#cmbDuplicateWith').combobox('showPanel');
        });
    });
    function formatCellStyler(val, row) {
        return "<a target='_blank' href='/Pages/Contact/ContactDetail.aspx?contact_id=" + row.ContactID + "'>View Profile</a>";
    }
    function formatDate(value, row) {
        if (result = false)
            return '';
        else {
            var date = new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var month = '';
            switch (m) {
                case 1:
                    month = 'Jan';
                    break;
                case 2:
                    month = 'Feb';
                    break;
                case 3:
                    month = 'Mar';
                    break;
                case 4:
                    month = 'Apr';
                    break;
                case 5:
                    month = 'May';
                    break;
                case 6:
                    month = 'Jun';
                case 7:
                    month = 'Jul';
                    break;
                case 8:
                    month = 'Aug';
                    break;
                case 9:
                    month = 'Sep';
                    break;
                case 10:
                    month = 'Oct';
                    break;
                case 11:
                    month = 'Nov';
                    break;
                case 12:
                    month = 'Dec';
                    break;
            }
            var d = date.getDate();
            return (d < 10 ? ('0' + d) : d) + ' ' + month + ' ' + y;
        }
    }
    function getSelectionsForApp() {
        var ss = [];
        var r = $('#cmbApplication').combogrid('grid');
        var rows = r.datagrid('getSelections');

        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            ss.push(row.app_id);
        }
        var_deleteApp = ss.join(',');
    }
    function getUnselectForApp() {
        var_deleteApp = '';
    }
    function startCounter(limit) {
        setTimeout(function () {
            if (limit == 0) {
                $('#lnkDeleteApplication').linkbutton('enable');
                $('#lnkCancle').linkbutton('enable');
                $('#spnanimate').hide();
            }
            else {
                $('#lbltimeOut').html(limit);
                startCounter(limit - 1);
            }
        }, 1000);
    }
    function detectByMultiple() {
        $('#divpreview').html('');
        $('#lbltemp').hide();
        $('#lblclientid').html('');
        var condition = $('#cmbMultiple').combobox('getValue');
        $('#hdnDetectiveBy').val(condition);
        $('#dgdetectClient').datagrid({
            url: '/WebServices/DuplicateContactDetective.ashx?method=GetDuplicateContactAll&searchfield=' + condition
        });
        $('#pnlClientDetail').hide();
    }
    function detectBySingle() {
        $('#divpreview').html('');
        $('#lbltemp').hide();
        $('#lblclientid').html('');
        var condition = $('#cmbSingle').combobox('getValue');
        $('#hdnDetectiveBy').val(condition);
        $('#dgdetectClient').datagrid({
            url: '/WebServices/DuplicateContactDetective.ashx?method=GetDuplicateContactAll&searchfield=' + condition
        });
        $('#pnlClientDetail').hide();
    }
    function OpenApplicationForm(appid) {
        var newWin = window.open('/pages/Application_Form.aspx?verified=0&id=' + appid, '_blank');
        newWin.focus();
    }
    function saveApplicationHistory(app_id) {
        var todaydate = new Date();
        var month = todaydate.getMonth() + 1;
        var hdate = month + '/' + todaydate.getDate() + '/' + todaydate.getFullYear();
        var hdesc = "Application " + app_id + " Deleted";
        var htime = todaydate.getHours() + ':' + todaydate.getMinutes() + ':' + todaydate.getSeconds();
        $.ajax({
            url: '/WebServices/History.ashx?method=saveNewHistory',
            contentType: "application/json; charset=utf-8",
            data: { 'HistoryType': 'Application', 'contactid': '0', 'hdate': hdate, 'htime': htime, 'action': 'Application Deleted (Detective) ', 'user': $('#hdnUserName').val(), 'description': hdesc, 'app_id': app_id, },
            success: function () {
            }
        });
    }

    function saveContactHistory(contactId, dupwithContact) {
        var operator = $('#hdnUserName').val();
        //insert to contact_history
        var desc = ' Remove the duplicated client= ' + contactId + ',to new client=' + dupwithContact;

        var currentDate = new Date()
        var day = currentDate.getDate()
        var month = currentDate.getMonth() + 1
        var year = currentDate.getFullYear()
        var HistoryDate = month + "/" + day + "/" + year;

        var currentTime = new Date()
        var HistoryTime =  currentTime.getHours() + ':' + currentTime.getMinutes() + ':' + currentTime.getSeconds();
        var Action = 'Remove Duplicated (Detective)';
        // insert history record for Current Client
        $.ajax({
            url: "/WebServices/History.ashx?method=saveNewHistory",
            data: {
                HistoryType: 'Contact', contactid: contactId, hdate: HistoryDate, htime: HistoryTime, action: Action,
                user: operator, description: desc, appid: '0'
            },
            success: function (result) {

            }
        });
        // insert history record for Duplicate Client

        $.ajax({
            url: "/WebServices/History.ashx?method=saveNewHistory",
            data: {
                HistoryType: 'Contact', contactid: dupwithContact, hdate: HistoryDate, htime: HistoryTime, action: Action,
                user: operator, description: Description, appid: '0'
            },
            success: function (result) {

            }
        });
    }
    function SubmitChanges() {
        if (var_deleteApp != '') {
            var arrApplicationDel = var_deleteApp.split(',');
            $.ajax({
                url: '/WebServices/ApplicationInfo.ashx?method=deleteMultipleApplications',
                contentType: "application/json; charset=utf-8",
                data: {
                    applications: var_deleteApp,
                    ContactID: $('#lblclientid').text()
                },
                success: function (data) {
                    $.messager.alert('Morgan CRM', 'Application Deleted');
                    $('#dgdetectClient').datagrid('reload');
                }
            });

            //add to history for each deleted application
            for (var j = 0; j < arrApplicationDel.length; j++) {
                saveApplicationHistory(arrApplicationDel[j]);
            }
            $('#cmbApplication').combogrid('clear');
            var_deleteApp = '';
        }
        if ($('#cmbDuplicateWith').combobox('getValue') != '') {
            var list_contacts = new Array();
            var arrDuplicateClient = [];
            var ContactsToDuplicat = '';
            list_contacts = $('#cmbDuplicateWith').combobox('getData');
            for (var i = 0; i < list_contacts.length; i++) {
                arrDuplicateClient.push(list_contacts[i].ContactID);
            }
            for (var i in arrDuplicateClient) {
                if (arrDuplicateClient[i] == $('#cmbDuplicateWith').combobox('getValue')) {
                    arrDuplicateClient.splice(i, 1);
                    break;
                }
            }
            ContactsToDuplicat = arrDuplicateClient.join(',');

            //Remove duplicate Client
            $.ajax({
                url: '/WebServices/DuplicateContactDetective.ashx?method=RemoveDuplicateContact',
                data: { ContactsToDuplicate: ContactsToDuplicat, DupWithContact: $('#cmbDuplicateWith').combobox('getValue') },
                success: function () {
                    $.messager.alert('Morgan CRM', 'Clients  ' + ContactsToDuplicat + ' duplicated Successfully ');
                    $('#dgdetectClient').datagrid('reload');
                    $('#pnlClientDetail').hide();
                }
            });

            //add history Record for each duplicated Client
            for (var i = 0; i < arrDuplicateClient.length ; i++) {
                saveContactHistory(arrDuplicateClient[i], $('#cmbDuplicateWith').combobox('getValue'));
            }
        }
    }
    function ShowClientDetail(contactid) {
        $.ajax({
            url: '/WebServices/ApplicationContact.ashx?method=ApplicationContactSelect&ContactID=' + contactid,
            success: function (data) {
                $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                    var previewData = " <br/><table style=\"width:auto\"> " +
                                    "<tr class=\"rowStyle\"> <td  class=\"CellStyle1\"> FullName </td>  <td class=\"CellStyle2\"> " + checkNull(rec.FirstName) + ' ' + checkNull(rec.MiddleName) + ' ' + checkNull(rec.SurName) + "</td> </tr> " +
                                    "<tr class=\"rowStyle\"><td  class=\"CellStyle1\"> DOB     </td>   <td class=\"CellStyle2\">" + formatDate(rec.DateBirth, null) + " </td></tr>" +
                                    "<tr class=\"rowStyle\"><td class=\"CellStyle1\"> E-Mail </td>    <td class=\"CellStyle2\">" + checkNull(rec.Email) + " </td></tr> " +
                                    "<tr class=\"rowStyle\"> <td class=\"CellStyle1\"> Mobile No.</td> <td class=\"CellStyle2\"> " + checkNull(rec.Mobile) + "</td></tr>" +
                                    "<tr class=\"rowStyle\"> <td class=\"CellStyle1\"> Home </td>      <td class=\"CellStyle2\"> " + checkNull(rec.HomePhone) + "</td></tr>" +
                                    "<tr class=\"rowStyle\"> <td class=\"CellStyle1\"> License No.</td><td class=\"CellStyle2\"> " + checkNull(rec.DriverLicense) + "</td></tr>" +
                                    "<tr class=\"rowStyle\"> <td class=\"CellStyle1\"> Citizenship</td><td class=\"CellStyle2\"> " + checkNull(rec.Citizenship) + "</td></tr>" +
                                    "<tr class=\"rowStyle\"> <td class=\"CellStyle1\"> Street</td>     <td class=\"CellStyle2\">" + checkNull(rec.Street) + "</td></tr>" +
                                    "<tr class=\"rowStyle\"> <td class=\"CellStyle1\"> Suburb</td>     <td class=\"CellStyle2\">" + checkNull(rec.Suburb) + "</td></tr>" +
                                    "<tr class=\"rowStyle\"> <td class=\"CellStyle1\"> State  </td>    <td class=\"CellStyle2\">" + checkNull(rec.State) + "</td></tr>" +
                                    "<tr class=\"rowStyle\"> <td class=\"CellStyle1\"> PostCode </td>  <td class=\"CellStyle2\">" + checkNull(rec.PostCode) + "</td></tr>" +
                                    "</table>";
                    $('#lbltemp').show();
                    $('#lblclientid').html(rec.ContactID);
                    $('#divpreview').html(previewData);
                });
            }
        });
    }
    function checkNull(value) {
        if (value == null)
            return value = '';
        else
            return value;
    }
    $('#dgdetectClient').datagrid({
        onLoadSuccess: function (data) {
            if (data.rows.length == 0)
                $('#divMsg').show();
            else
                $('#divMsg').hide();
        },
        onClickRow: function (index, rowdata) {
            $('#cmbApplication').combogrid('clear');
            var_deleteApp = '';
            ShowClientDetail(rowdata.ContactID);

            //Get All Applicatin for current ContactID
            $('#cmbApplication').combogrid({
                panelWidth: 150,
                multiple: true,
                idField: 'app_id',
                textField: 'app_id',
                editable: true,
                url: '/WebServices/ApplicationContact.ashx?method=GetApplicationForClient&ContactID=' + rowdata.ContactID,
                columns: [[
                    { field: 'ck', checkbox: true },
                    { field: 'app_id', width: 80 },
                ]],
                onSelect: getSelectionsForApp,
                onUnselect: getUnselectForApp,
                fitColumns: true
            });

            //fill DropDown
            $('#hdnDetectivBy').val(rowdata.DetectiveBy);
            var pager = $('#dgdetectClient').datagrid('options');
            var currentPageNumber = pager.pageNumber;
            var list_contacts = new Array();
            list_contacts = $('#cmbDuplicateWith').combobox('getData');
            var temp = '';
            for (var i = 0; i < list_contacts.length; i++) {
                temp += list_contacts[i].ContactID + ',';
            }
            $('#cmbDuplicateWith').combobox({
                url: '/WebServices/DuplicateContactDetective.ashx?method=GetDuplicatedContactID&field=' + $('#hdnDetectiveBy').val() + '&value=' + rowdata.DetectiveBy,
                valueField: 'ContactID',
                textField: 'ContactID'
            });
            $('#pnlClientDetail').show();
            $('#cmbDuplicateWith').combobox('setText', '<-- Select -->');
        }
    });
</script>
</html>
